<?php

namespace app\admin\controller;

use app\admin\common\Base;
use app\admin\model\Products as ProductsModel;
use think\Db;
use PHPExcel;

class Product extends Base {
    /**
     * 组装查询条件
     * @param $keyword
     * @param $category
     * @return array
     */
    protected function getCondition($keyword, $category){
        $condition[] = ['is_del', '=', 0];

        if (!empty($keyword)) {
            $condition[] = ['id|name', 'like', '%' . $keyword . '%'];
        }

        if (!empty($category)) {
            $child = $this->getAllChild($category, 'category_product');

            if (!empty($child)) {
                //有子级
                array_push($child, intval($category));
                $condition[] = ['category', 'in', $child];
            } else {
                //无子级
                $condition[] = ['category', '=', $category];
            }
        }

        return $condition;
    }

    public function index($page = 1,$limit = 10,$keyword = '',$category = ''){
        if (is_post()){
            $where = $this->getCondition($keyword,$category);

            $data = $this->getListData('product',$where,'sort','asc',$page,$limit);

            $type = db('category_product')->select();
            $type = to_dict($type);
            if (!empty($data['list'])){
                foreach ($data['list'] as $k => $v){
                    $data['list'][$k]['category_name'] = $type[$v['category']];
                }
            }
            return json(['code' => 'suc', 'msg' => '数据请求成功', 'count' => $data['count'], 'data' => $data['list'], 'current_page' => $page]);
        }
        $this->assign('category',$this->getCategory());
        return $this->fetch();
    }

    public function add(){
        if (is_post()){
            //实例化模型
            $model = new ProductsModel();
            //接收数据
            $data = input('post.');
            //执行添加操作
            $result = $model->add($data);

            return json(['code' => $result['code'], 'msg' => $result['msg']]);
        }
        $all_products = $this->getAllProducts();
        $this->assign('all_products',json_encode($all_products));
        $tree_type_list = $this->getCategory();
        $this->assign('category',$tree_type_list);
        return $this->fetch();
    }

    public function edit($id){
        if (is_post()){
            //实例化模型
            $model = new ProductsModel();
            //接收数据
            $data = input('post.');
            //执行修改操作
            $result = $model->edit($id,$data);
            return json(['code'=>$result['code'],'msg'=>$result['msg']]);
        }
        $tree_type_list = $this->getCategory();
        $info = db('product')
            ->where('id',$id)
            ->find();
        $all_products = $this->getAllProducts($id);
        $this->assign('all_products',json_encode($all_products));
        $info['carousel'] = json_decode($info['carousel'],true);
        $info['carousel_json'] = json_encode($info['carousel']);
        $related_products = array_filter(explode(',',$info['related_products']));
        $this->assign('related_products',json_encode($related_products));
        $this->assign('category',$tree_type_list);
        $this->assign('info',$info);
//        dump($info);
        return $this->fetch();
    }

    public function copy($data){
        if (is_post()){
            $data = json_decode($data,true);

            $ids = [];
            foreach ($data as $k => $v){
                array_push($ids,intval($v['id']));
                $data[$k]['create_time'] = time();
                $data[$k]['update_time'] = time();

                if (!empty($v['seo_link'])){
                    $data[$k]['seo_link'] = $v['seo_link'] . mt_rand(0,99);
                }

                unset($data[$k]['id']);
                unset($data[$k]['category_name']);
            }

            $ids = implode(',',$ids);
            $result = db('product')->data($data)->insertAll($data);
            if ($result){
                insert_system_log('复制产品：' . $ids);
                return json(['code' => 'suc', 'msg' => '复制成功']);
            }else{
                return json(['code' => 'err', 'msg' => '系统繁忙，请重试']);
            }
        }
    }

    public function del($id){
        if (is_post() && $this->delRecord('product', $id, '删除产品：')) {
            return json(['code' => 'suc', 'msg' => config('msg.del_suc')]);
        }
        return json(['code' => 'err', 'msg' => config('msg.err_msg')]);
    }

    /**
     * 修改产品状态
     * @param int|string $id 产品id
     * @param int $type 操作类型 1：开启 other：关闭
     * @param int $field 数据表对应字段 1：status  2:is_recommended  3:is_hot
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function changeStatus($id,$type,$field){
        if (is_post()){
            switch ($field){
                case 1:
                    $log_action = $type==1 ? '显示' : '隐藏';
                    $action_str = $type==1 ? '已显示' : '已隐藏';
                    break;
                case 2:
                    $log_action = $type==1 ? '推荐' : '取消推荐';
                    $action_str = $type==1 ? '已推荐' : '取消推荐';
                    break;
                case 3:
                    $log_action = $type==1 ? '设置为热销' : '取消热销产品';
                    $action_str = $type==1 ? '已设置为热销' : '已取消热销产品';
                    break;
                default:
                    $log_action = $type==1 ? '显示' : '隐藏';
                    $action_str = $type==1 ? '已显示' : '已隐藏';
            }

            if ($this->changeRecordStatus('product',$id,$field,$type)){
                insert_system_log($log_action . '产品：' . $id);
                return json(['code' => 'suc', 'msg' => $action_str . '产品']);
            }
            return json(['code' => 'err','msg' => config('msg.err_msg')]);

        }
    }

    public function upload(){
        $file = request()->file('file');
        $info = $this->uploadsImg($file,'uploads/product/');
        if ($info !== false){
            return json(['code' => 'suc','msg' => '图片上传成功','url' => $info['path'],'file_name'=>$info['file_name']]);
        }else{
            return json(['code' => 'err','msg' => '图片上传失败，请重试']);
        }
    }

    /**
     * 获取所有产品分类
     * @return mixed
     */
    public function getCategory(){
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $list = $this->getListData('category_product',$where,'sort','asc',1,1000);
        return $this->getTree($list['list']);
    }

    /**
     * 获取所有产品
     * @param string $id 需要排除的产品ID，因为不需要关联自己
     * @return mixed
     */
    public function getAllProducts($id=''){
        if (!empty($id)){
            $where[] = ['id','<>',$id];
        }
        $where[] = ['is_del','=',0];
        $where[] = ['status','=',1];
        $all_products = db('product')
            ->where($where)
            ->field('id as value,name as title')
            ->select();
        foreach ($all_products as $k => $v){
            $all_products[$k]['disabled'] = "";
            $all_products[$k]['checked'] = "";
        }
        return $all_products;
    }

    public function template()
    {
        try {
            $file_name = "category.xlsx"; // 文件名
            $root_path = app()->getRootPath();
            $file_dir = $root_path . 'public/static/excel/'; // 文件路径
            if (!file_exists($file_dir . $file_name)) { // 判断文件是否存在
                header('HTTP/1.1 404 NOT FOUND');
            } else {
                //以只读和二进制模式打开文件
                $file = fopen($file_dir . $file_name, "rb");
                //告诉浏览器这是一个文件流格式的文件
                header("Content-type:application/octet-stream");
                //请求范围的度量单位
                header("Accept-Ranges:bytes");
                //Content-Length是指定包含于请求或响应中数据的字节长度
                header("Accept-Length:" . filesize($file_dir . $file_name));
                //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
                header("Content-Disposition:attachment;filename=产品分类导入模板.xlsx");
                //读取文件内容并直接输出到浏览器
                echo fread($file, filesize($file_dir . $file_name));
                fclose($file);
                exit();
            }
        } catch (\Throwable $th) {
            // dump($th);
        }
    }
    public function uplodExcel($file,$save_path){
        $config = [
            'size' => 5242880,//最大允许上传1M
            'ext' => 'xls,xlsx'//允许上传的文件类型
        ];

        $file_name = $file->getInfo()['name'];
        $file_name = substr($file_name,0,strrpos($file_name,'.'));
        
        $info = $file
            ->validate($config)
            ->move($save_path);
        if ($info){
            return ['path' => '/' . $save_path . $info->getFilename(),'file_name' =>$file_name];
        }else{
            return false;
        }
    }
    //查重
    public function find_repeat_term($name){
        $find_data = db('product_type')->where([
            "name" => $name
        ])->find()['name'];
        if(!$find_data){
            return false;
        }else{
            return true;
        }
    }
    public function import(){
        try {
            $f = [];
            $file = request()->file('file');
            $info = $this->uplodExcel($file,'uploads/excel/');
            if (!$info){
                $re['code'] = 100;
                $re['msg'] = '请上传excel格式的文件';
                echo json_encode($re);
                exit();
            }
            //实例化类库
            $phpExcel = new PHPExcel;
            $reader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objData = $reader->load('.'.$info['path']);
            $excel_array = $objData->getsheet(0)->toArray();
            $sheet = $objData->getSheet(0); //读取第一张表
            $row_num = $sheet->getHighestRow();//获取总行数
            array_shift($excel_array);
            $excel_data = [];
            //删除空白行的数据
            foreach ($excel_array as $excel_array_key => $excel_array_value) {
                $excel_array_null = 0;
                foreach ($excel_array_value as $excel_array_value_key => $excel_array_value_value) {
                    $excel_array[$excel_array_key][$excel_array_value_key] = trim($excel_array_value_value);
                    if (trim($excel_array_value_value) === "" || trim($excel_array_value_value) === null) {
                        $excel_array_null++;
                    }
                }
                if (count($excel_array_value) !== $excel_array_null) {
                    array_push($excel_data, $excel_array[$excel_array_key]);
                }
            }
            if(count($excel_data) === 0){
                $re['code'] = 101;
                $re['msg'] = '请填写数据再上传';
                echo json_encode($re);
                exit();
            }else{
                foreach($excel_data as $excel_data_key => $excel_data_value){
                    $line = $excel_data_key + 2; //行数
                    $find_parent_name = $this->find_repeat_term($excel_data_value[0]);//查重
                    if($find_parent_name == false){
                        $data = [];
                        $data['name'] = $excel_data_value[0];
                        $data['is_recommended'] = empty($excel_data_value[1]) ? 0 : ($excel_data_value[1] == '是' ? 1 : 0);
                        $data['sort'] = empty($excel_data_value[2]) ? 255 : $excel_data_value[2];
                        $data['create_time'] = time();
                        $data['update_time'] = time();
                        $insert_data = db('product_type')->insertGetId($data);

                        if(!empty($excel_data_value[3])){
                            $child_name = array_filter(explode(',',$excel_data_value[3]));
                            foreach($child_name as $child_name_key => $child_name_value){
                                $find_child_name = $this->find_repeat_term($child_name_value);//查重
                                if($find_child_name == false){
                                    $insert_child_data  = db('product_type')->insert([
                                        "pid" => $insert_data,
                                        "name" => $child_name_value,
                                        "sort" => $child_name_key + 1,
                                        "is_recommended" => 0,
                                        "create_time" => time(),
                                        "update_time" => time(),
                                    ]);
                                }
                            }
                        }
                        if ($insert_data) {
                            Db::commit();
                            array_push($f, "第" . $line . "行，数据库保存成功");
                            $re = [
                                "code" => 200,
                                "msg" => join("<br>", $f)
                            ];
                        } else {
                            Db::rollback();
                            array_push($f, "第" . $line . "行，数据库保存失败");
                            $re = [
                                "code" => 103,
                                "msg" => join("<br>", $f)
                            ];
                        }
                    }else{
                        array_push($f, "第" . $line . "行，已存在该分类");
                        $re = [
                            "code" => 102,
                            "msg" => join("<br>", $f)
                        ];
                    }
                }
            }
        } catch (\Throwable $th) {
            dump($th);
        }
        return json($re);
    }
}